package com.chaos.auth.config.granter.user;

import cn.hutool.core.lang.Assert;
import com.chaos.auth.api.dto.token.UserAuthenticationToken;
import com.chaos.auth.service.userdetails.UserByPhoneDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class UserByPhoneAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserByPhoneDetailsService userByPhoneDetailsService;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //先将authentication转为我们自定义的Authentication对象
        Map<String, String> details = (Map<String, String>) authentication.getPrincipal();
        String phone = details.get("phone");
        Assert.notNull(phone, "手机号不能为空");
        //校验参数
        UserDetails userDetails = userByPhoneDetailsService.loadUserByPhone(phone,null);
        if (userDetails == null) {
            throw new InternalAuthenticationServiceException("用户手机不存在！");
        }
        //返回认证成功的对象
        UserAuthenticationToken result = new UserAuthenticationToken(userDetails);
        result.setPhone(phone);
        result.setDetails(authentication.getDetails());
        return result;
    }


    @Override
    public boolean supports(Class<?> authentication) {
        return UserAuthenticationToken.class.isAssignableFrom(authentication);
    }

}
